using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
using Serilog;
using Serilog.Events;

namespace Ec.NETCoreFramework.Common.Plug.QuartzService
{
    public class Program
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
       .SetBasePath(Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .AddEnvironmentVariables()
       .Build();

        public static void Main(string[] args)
        {
            string path = Path.Combine(Directory.GetCurrentDirectory(), "log",
                        "Ec.NETCoreFramework.Common.Plug.QuartzService");
            const string outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.FFF}-{RequestId} {Level}] {Message}({SourceContext:l}){NewLine}{Exception}";
            var sentryUrl = Configuration.GetValue<string>("SentryUrl");
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .Enrich.FromLogContext()
                .Enrich.WithThreadId()
                 .WriteTo.Sentry(sentryUrl, serverName: "quartz-service", environment: Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), minimumBreadcrumbLevel: LogEventLevel.Information, minimumEventLevel: LogEventLevel.Information)
                .WriteTo.File(path, rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, outputTemplate: outputTemplate)
                .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
                    services.AddHostedService<QuartzHostedService>();
                   // services.AddHostedService<Worker>();
                });
    }
}
